﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace ResourceReportBuilder
{
    internal static class DrawingUtilities
    {
        public static void DrawString(Graphics graphics, string s, Font font, Brush brush, Rectangle clientRectangle)
        {
            DrawString(graphics, s, font, brush, clientRectangle, null);
        }

        public static void DrawString(Graphics graphics, string s, Font font, Brush brush, Rectangle clientRectangle, StringFormat format)
        {
            int y = (clientRectangle.Height - (int)GetTextHeight(graphics, s, font)) / 2;
            if (format != null)
            {
                graphics.DrawString(GetAllowedString(graphics, s, font, clientRectangle.Width), font, brush, 0, y, format);
            }
            else
            {
                graphics.DrawString(GetAllowedString(graphics, s, font, clientRectangle.Width), font, brush, 0, y);
            }
        }

        public static void DrawStringDisabled(Graphics graphics, string s, Font font, Color color, Rectangle clientRectangle, StringFormat format)
        {
            int y = clientRectangle.Height - (int)(GetTextHeight(graphics, s, font) / 2);
            Rectangle clRect = clientRectangle;
            //clRect
            ControlPaint.DrawStringDisabled(graphics, GetAllowedString(graphics, s, font, clRect.Width), font, Color.White, clRect, format);
        }

        private static int GetTextHeight(Graphics g, string s, Font font)
        {
            SizeF sz = g.MeasureString(s, font);
            return (int)Math.Ceiling(sz.Height);
        }

        private static string GetAllowedString(Graphics g, string s, Font font, int textWidth)
        {
            string sRet = s;
            SizeF sz = g.MeasureString(s, font);
            if (sz.Width > textWidth)
            {
                sRet = sRet.Substring(0, sRet.Length - 3) + "...";
            }
            else
            {
                return s;
            }
            while (g.MeasureString(sRet, font).Width > textWidth)
            {
                if (sRet.EndsWith("..."))
                {
                    sRet = sRet.Substring(0, sRet.Length - 4) + "...";
                }
                else
                {
                    sRet = sRet.Substring(0, sRet.Length - 1) + "...";
                }
            }
            return sRet;
        }
    }
}
